package o2o.web.actions.shop;

import com.jinyou.utils.common.*;
import o2o.cache.agent.AgentManagerMemory;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.order.user.UserOrderMemoryMan;
import o2o.cache.shop.*;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.AgentManagerInfo;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.shop.*;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.area.RegionInfoVO;
import o2o.dao.VO.order.REFUND_APPLY_STATUS;
import o2o.dao.VO.shop.*;
import o2o.service.shop.ShopService;
import o2o.company.model.ShopInfo;
import o2o.system.data.SYS_SETTINGS;
import o2o.task.image.ImageService;
import o2o.web.actions.company.SysCityCompanyMan;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static o2o.web.actions.order.OrderListMan.getShopIdList;


@Controller
public class ShopListAction {

    //获取全部店铺，不用任何参数
    @RequestMapping(method = RequestMethod.POST, value = "/sys/all/shop/list")
    @ResponseBody
    public String getAllShopList() {
        List<ShopInfo> shopList = ShopMemory.getInstance().list();
        if (ValidateUtil.isAbsList(shopList)) {
            List<Object> reList = new ArrayList<>();
            for (int i = 0; i < shopList.size(); i++) {
                if (null == shopList.get(i)) {
                    continue;
                }
                Map<String, Object> data = new HashMap<>();
                data.put("id", shopList.get(i).getId());
                data.put("ownUsername", shopList.get(i).getOwnUsername());
                data.put("shopName", shopList.get(i).getShopName());
                reList.add(data);
            }
            if (ValidateUtil.isAbsList(reList)) {
                return AjaxResult.successResult(reList.size(), reList);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    // 获取常卖店铺
    @RequestMapping(method = RequestMethod.POST, value = "/user/often/sold/shop/list")
    @ResponseBody
    public String userOftenSoldShop(String sysAppKey, String token, Integer buyCount,
                                    @RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.successResult(null, 0);
        }
        List<OrderInfo> list = UserOrderMemoryMan.listOfUser(user.getUsername(), null);
        if (list == null) {
            return AjaxResult.successResult(null, 0);
        }
        Map<Long, Integer> sizeMap = new HashMap<>();
        for (OrderInfo info : list) {
            if (info == null) {
                continue;
            }
            if (ValidateUtil.isNotID(info.getShopId()) || ORDER_STATUS.OVER != info.getOrderStatus() || REFUND_APPLY_STATUS.PASS == info.getIsRefundApply()) {
                continue;
            }
            if (sizeMap.keySet().contains(info.getShopId())) {
                Integer count = sizeMap.get(info.getShopId());
                count++;
                sizeMap.put(info.getShopId(), count);
            } else {
                sizeMap.put(info.getShopId(), 1);
            }
        }
        if (!sizeMap.isEmpty()) {
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Long key : sizeMap.keySet()) {
                Integer count = sizeMap.get(key);
                if (buyCount != null && count < buyCount) {
                    continue;
                }
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(key);
                if (shopInfo == null) {
                    continue;
                }
                Map<String, Object> resultOne = new HashMap<>();
                resultOne.put("id", shopInfo.getId());
                resultOne.put("shopName", shopInfo.getShopName());
                resultOne.put("shopNameLang", shopInfo.getShopNameLang());
                if (ValidateUtil.isNotNull(shopInfo.getImageUrl())) {
                    if (ValidateUtil.isNotNetUrl(shopInfo.getImageUrl())) {
                        resultOne.put("imageThumbnailUrl", ImageService.getThumbnailImgUrl(shopInfo.getImageUrl(), shopInfo.getImgUpVer(), shopInfo.getThumbnailState()));
//                        resultOne.put("imageUrl", SYS_CONFIG_PATH.IMAGE_BASE_URL + shopInfo.getImageUrl());
                        resultOne.put("imageUrl", ImageService.getImgUrl(shopInfo.getImgUpVer()) + shopInfo.getImageUrl());
                    } else {
                        resultOne.put("imageUrl", shopInfo.getImageUrl());
                    }
                }
                resultOne.put("userBuyCount", count);
                resultOne.put("isWork", shopInfo.getIsWork());
                resultList.add(resultOne);
            }
            if (ValidateUtil.isAbsList(resultList)) {
                Collections.sort(resultList, Comparator.comparingInt(e -> {
                    return e.get("userBuyCount") == null ? 0 : Integer.parseInt(e.get("userBuyCount").toString());
                }));
                JYPageUtils.PageList pageList = JYPageUtils.getList(resultList, page, size);
                return AjaxResult.successResult(pageList.list, pageList.totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    //获取首页猜你喜欢店铺列表  无活动
    @RequestMapping(method = RequestMethod.POST, value = "/home/recommend/shop/list")
    @ResponseBody
    public String recommend_shop_list(String token, String province,
                                      String city,
                                      Double lng, Double lat,
                                      String county,
                                      String region,//粗略的 商圈
                                      Long agentId,//精确的商圈(等我5分钟在用)
                                      Integer orderType,//排序方式
                                      String filterType,
                                      Integer needGoods, // 店铺需要返回商品列表
                                      Integer needGoodsCount, // 店铺需要返回商品列表
                                      Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请先选择城市");
        }

        JYPageUtils.PageList pageList = ShopListMan.getShopList(user,//获取首页猜你喜欢店铺列表  无活动
                false,//checkTypeId
                null,//typeId
                city,//city
                null,//regionId
                agentId,
                lng, lat,
                null,//content
                true,//checkRecommend
                true,//isRecommend
                false,//hasGameInfo
                orderType,
                filterType,
                null,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                null,
                page, size);
        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    /**
     * 代理
     *
     * @param token
     * @param agentId
     * @param getNextLevel
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/admin/recommend/shop/list")
    @ResponseBody
    public String recommend_shop_list(String token,
                                      Long agentId,
                                      Integer typeId,
                                      String content,
                                      Integer getNextLevel,
                                      Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (user.getUserType() != UserType.ADMIN) {
            return AjaxResult.successResult(0, 0, null);
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }


        return AjaxResult.successResult(0, 0, null);
    }


    //获取首页猜你喜欢店铺列表  包含活动信息
    @RequestMapping(method = RequestMethod.POST, value = "/home/recommend/shop/withGame/list")
    @ResponseBody
    public String recommend_shop_with_game_list(String token, String city, String county,
                                                Long agentId,//商圈Id
                                                Integer orderType,//排序方式
                                                String filterType,
                                                Integer needGoods, // 店铺需要返回商品列表
                                                Integer needGoodsCount, // 店铺需要返回商品列表
                                                Integer needResultGoodsNumber,
                                                Double lng, Double lat, Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (null != SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG && 0 == 1 - SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG) {

        } else {
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("请先选择城市");
            }
        }
        FilterConditionUtils conditionUtils = FilterConditionUtils.getInstance();
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            conditionUtils.setCheckCloudSquareShop(true);
        }
        conditionUtils.setNeedResultGoodsNumber(needResultGoodsNumber);
        JYPageUtils.PageList pageList = ShopListMan.getShopList(user, // 获取首页猜你喜欢店铺列表 包含活动信息
                false,//checkTypeId
                null,//typeId
                city,//city
                null,//regionId
                agentId,
                lng, lat,
                null,//content
                true,//checkRecommend
                true,//isRecommend
                true,//hasGameInfo
//                false,
//                false,
                orderType,
                filterType,
                null,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                conditionUtils,
                page, size);

        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }

        return AjaxResult.successResult(0, 0, null);
    }


    private boolean validTime(String localTime, String time) {
        if (ValidateUtil.isNull(time)) {
            return false;
        }
        String[] split = StringUtils.split(time, "-");
        if (split.length != 2) {
            return false;
        }
        try {
            Integer now = Integer.parseInt(localTime);
            Integer start = Integer.parseInt(split[0].replaceAll(":", ""));
            Integer end = Integer.parseInt(split[1].replaceAll(":", ""));
            if (start > end && (now >= start || now <= end)) {
                return true;
            } else if (start < end && (now >= start && now <= end)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }


    //获取首页优选店铺列表  无活动
    @RequestMapping(method = RequestMethod.POST, value = "/isPreference/shop/list")
    @ResponseBody
    public String isPreference_shop_list(String token, String province,
                                         String city,
                                         Double lng, Double lat,
                                         String county,
                                         String region,//粗略的 商圈
                                         Long agentId,//精确的商圈(等我5分钟在用)
                                         Integer orderType,//排序方式
                                         String filterType,
                                         Integer needGoods, // 店铺需要返回商品列表
                                         Integer needGoodsCount, // 店铺需要返回商品列表
                                         Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请先选择城市");
        }

        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }
        JYPageUtils.PageList pageList = ShopListMan.getShopList(user, // 获取首页猜你喜欢店铺列表 包含活动信息
                false,//checkTypeId
                null,//typeId
                city,//city
                null,//regionId
                agentId,
                lng, lat,
                null,//content
                false,//checkRecommend
                false,//isRecommend
                true,//checkIsPreference
                true,//isPreference
                false,// 有没有活动
                orderType,
                filterType,
                null,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                null,
                page, size);
        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    // 获取优选的店铺列表  包含活动信息
    @RequestMapping(method = RequestMethod.POST, value = "/isPreference/shop/withGame/list")
    @ResponseBody
    public String isPreference_shop_with_game_list(String token, String province, String city, String county, String region, Long regionId,
                                                   Long agentId,//商圈Id
                                                   Integer orderType,//排序方式
                                                   String filterType,
                                                   Integer needGoods, // 店铺需要返回商品列表
                                                   Integer needGoodsCount, // 店铺需要返回商品列表
                                                   String devJson,
                                                   Double lng, Double lat, Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (null != SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG && 0 == 1 - SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG) {

        } else {
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("请先选择城市");
            }
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }
        JYPageUtils.PageList pageList = ShopListMan.getShopList(user, // 获取首页猜你喜欢店铺列表 包含活动信息
                false,//checkTypeId
                null,//typeId
                city,//city
                null,//regionId
                agentId,
                lng, lat,
                null,//content
                false,//checkRecommend
                false,//isRecommend
                true,//checkIsPreference
                true,//isPreference
                true,// 有没有活动
                orderType,
                filterType,
                null,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                null,
                page, size);

        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }

        return AjaxResult.successResult(0, 0, null);
    }


    //-----------------------------------------------不同类型店铺列表
    //获取不同类型的店铺 用户端  无活动
    @RequestMapping(method = RequestMethod.POST, value = "/shop/list")
    @ResponseBody
    public String list(String token, String content,
                       Integer typeId,
                       String city,
                       Double lng, Double lat,
                       String searchType, String province, String county,
                       String region,//粗略的 商圈
                       Long regionId,
                       Long agentId, //精确的商圈(等我5分钟在用)
                       Integer orderType,//排序方式
                       String filterType,
                       Integer needGoods, // 店铺需要返回商品列表
                       Integer needGoodsCount, // 店铺需要返回商品列表
                       Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请先选择城市");
        }

        JYPageUtils.PageList pageList = ShopListMan.getShopList(user,//获取不同类型的店铺 用户端  无活动
                true,//checkTypeId
                typeId,//typeId
                city,//city
                regionId,//regionId
                agentId,
                lng, lat,
                content,//content
                false,//checkRecommend
                null,//isRecommend
                false,//hasGameInfo
                orderType,
                filterType,
                null,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                null,
                page, size);
        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }

//        List<ShopInfo> list = null;
//        if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)) {//有经纬度根据经纬度来
//            Long areaPoint = Geohash.getArea(lat, lng);
//
//            int range = 15;//大概是10公里
//            if (ValidateUtil.isAbsInteger(SYS_SETTINGS.SHOP_RANGE)) {
//                range = SYS_SETTINGS.SHOP_RANGE;
//            }
//            Set<Long> areaPoints = Geohash.getAroundArea(areaPoint, range);//大概是10公里
//
//
//            List<ShopInfo> tmp = null;
//            if (ValidateUtil.isID(regionId)) {
//                tmp = new ArrayList<ShopInfo>();
//                List<ShopRegionRelation> relationList = ShopRegionRelationMemory.getInstance().listOfRegionId(regionId);
//                if (ValidateUtil.isAbsList(relationList)) {
//                    for (int i = 0; i < relationList.size(); i++) {
//                        if (null == relationList.get(i)) {
//                            continue;
//                        }
//                        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(relationList.get(i).getShopId());
//                        tmp.add(shopInfo);
//                    }
//                }
//            } else {
//                tmp = ShopMemory.getInstance().list(typeId, city, "", "", content, false);//该城市店铺列表
//            }
//
//
//            if (ValidateUtil.isAbsList(tmp)) {
//                list = new ArrayList<ShopInfo>();
//                for (int i = 0; i < tmp.size(); i++) {
//                    if (null == tmp.get(i)) {
//                        continue;
//                    }
//                    if (ValidateUtil.isNotAbsDouble(lat) || ValidateUtil.isNotAbsDouble(lng)) {
//                        continue;
//                    }
//                    if (ValidateUtil.isNotAbsLong(tmp.get(i).getAreaPoint())) {
//                        continue;
//                    }
//                    if (!areaPoints.contains(tmp.get(i).getAreaPoint())) {
//                        continue;
//                    }
////                    tmp.get(i).setAreaLong(Math.abs(tmp.get(i).getAreaPoint() - areaPoint));
//                    tmp.get(i).setDistinct(Geohash.distance(lat, lng, tmp.get(i).getLat(), tmp.get(i).getLng()));
//                    list.add(tmp.get(i));
//                }
//
////                //默认按照距离排序
////                Collections.sort(list, new Comparator<ShopInfo>() {
////                    public int compare(ShopInfo arg0, ShopInfo arg1) {
////                        return arg0.getAreaLong().compareTo(arg1.getAreaLong());//倒叙排列
////                    }
////                });
//
//                //默认按照距离排序
//                Collections.sort(list, new Comparator<ShopInfo>() {
//                    public int compare(ShopInfo arg0, ShopInfo arg1) {
//                        return arg0.getDistinct().compareTo(arg1.getDistinct());//倒叙排列
//                    }
//                });
//            }
//        } else {
//            list = ShopMemory.getInstance().list(typeId, city, county, region, content, false);//该城市店铺列表
//        }
//
//        if (!ValidateUtil.isAbsList(list)) {
//            return AjaxResult.successResult(0, null);
//        }
//
//        if (ValidateUtil.isNotAbsInteger(page) || page < 1) {
//            page = 1;
//        }
//        if (ValidateUtil.isNotAbsInteger(size) || size < 1) {
//            size = 10;
//        }
//
//
//        //把推荐的店铺放在上面
//        List<ShopInfo> reList = new ArrayList<>();
//        if (ValidateUtil.isAbsList(list)) {
//            for (int i = 0; i < list.size(); i++) {
//                if (null == list.get(i)) {
//                    continue;
//                }
//                if (0 == 1 - list.get(i).getIsRecommend()) {
//                    reList.add(list.get(i));
//                }
//            }
//            for (int i = 0; i < list.size(); i++) {
//                if (null == list.get(i)) {
//                    continue;
//                }
//                if (0 == list.get(i).getIsRecommend()) {
//                    reList.add(list.get(i));
//                }
//            }
//        }
//
//
//        JYPageUtils.PageList pageList = JYPageUtils.getList(reList, page, size);
//        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
//            List<ShopInfoVO> voList = new ArrayList<ShopInfoVO>();
//            for (int i = 0; i < pageList.list.size(); i++) {
//                if (null == pageList.list.get(i)) {
//                    continue;
//                }
////                ShopInfoVO shopInfoVO = new ShopInfoVO();
////                try {
////                    ObjectUtils.copyPropertiesExclude(pageList.list.get(i), shopInfoVO, null);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                    continue;
////                }
////                if (null == shopInfoVO) {
////                    continue;
////                }
//
//
//                ShopInfoVO shopInfoVO = Shop.getBaseOne(null, (ShopInfo) pageList.list.get(i));
//                if (null == shopInfoVO) {
//                    continue;
//                }
//
//                List<RegionInfoVO> relationList = Shop.getRegionListOfShop(shopInfoVO.getId());
//                if (ValidateUtil.isAbsList(relationList)) {
//                    shopInfoVO.setRegions(relationList);
//                }
//                voList.add(shopInfoVO);
//            }
//
//            if (ValidateUtil.isAbsList(voList)) {
//                return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
//            }
//        }


        return AjaxResult.successResult(0, 0, null);
    }


    //获取不同类型的店铺 用户端  包含活动信息
    @RequestMapping(method = RequestMethod.POST, value = "/shop/withGame/list")
    @ResponseBody
    public String list_with_game(String token, String content,
                                 Integer typeId,
                                 String city,
                                 Double lng, Double lat,
                                 String searchType, String province, String county,
                                 String region,//粗略的 商圈
                                 Long regionId,
                                 Long agentId, //精确的商圈(等我5分钟在用)
                                 Integer orderType,//排序方式
                                 String filterType,
                                 @RequestParam(defaultValue = "1") Integer shopCategory, //  默认是表示外卖商家
                                 Integer needGoods, // 店铺需要返回商品列表
                                 Integer needGoodsCount, // 店铺需要返回商品列表
                                 String devJson,// 设备信息
                                 Integer page, Integer size) {

        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请先选择城市");
        }
        FilterConditionUtils filterConditionUtils = FilterConditionUtils.getInstance();
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            filterConditionUtils.setCheckCloudSquareShop(true);
        }
        JYPageUtils.PageList pageList = ShopListMan.getShopList(user,//获取不同类型的店铺 用户端  包含活动信息
                true,//checkTypeId
                typeId,//typeId
                city,//city
                regionId,//regionId
                agentId,
                lng, lat,
                content,//content
                false,//checkRecommend
                null,//isRecommend
                true,//hasGameInfo
                orderType,
                filterType,
                shopCategory,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                filterConditionUtils,
                page, size);
        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }

//        if (ValidateUtil.isNull(city)) {
//            return AjaxResult.errorResult("请先选择城市");
//        }
//
//        List<ShopInfo> list = null;
//        if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)) {//有经纬度根据经纬度来
//            Long areaPoint = Geohash.getArea(lat, lng);
//
//            int range = 15;//大概是10公里
//            if (ValidateUtil.isAbsInteger(SYS_SETTINGS.SHOP_RANGE)) {
//                range = SYS_SETTINGS.SHOP_RANGE;
//            }
//            Set<Long> areaPoints = Geohash.getAroundArea(areaPoint, range);//大概是10公里
//
//
//            List<ShopInfo> tmp = null;
//            if (ValidateUtil.isID(regionId)) {
//                tmp = new ArrayList<ShopInfo>();
//                List<ShopRegionRelation> relationList = ShopRegionRelationMemory.getInstance().listOfRegionId(regionId);
//                if (ValidateUtil.isAbsList(relationList)) {
//                    for (int i = 0; i < relationList.size(); i++) {
//                        if (null == relationList.get(i)) {
//                            continue;
//                        }
//                        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(relationList.get(i).getShopId());
//                        tmp.add(shopInfo);
//                    }
//                }
//            } else {
//                tmp = ShopMemory.getInstance().list(typeId, city, "", "", content, false);//该城市店铺列表
//            }
//
//
//            if (ValidateUtil.isAbsList(tmp)) {
//                list = new ArrayList<ShopInfo>();
//                for (int i = 0; i < tmp.size(); i++) {
//                    if (null == tmp.get(i)) {
//                        continue;
//                    }
//                    if (ValidateUtil.isNotAbsDouble(lat) || ValidateUtil.isNotAbsDouble(lng)) {
//                        continue;
//                    }
//                    if (ValidateUtil.isNotAbsLong(tmp.get(i).getAreaPoint())) {
//                        continue;
//                    }
//                    if (!areaPoints.contains(tmp.get(i).getAreaPoint())) {
//                        continue;
//                    }
////                    tmp.get(i).setAreaLong(Math.abs(tmp.get(i).getAreaPoint() - areaPoint));
//                    tmp.get(i).setDistinct(Geohash.distance(lat, lng, tmp.get(i).getLat(), tmp.get(i).getLng()));
//                    list.add(tmp.get(i));
//                }
//
//                //默认按照距离排序
////                Collections.sort(list, new Comparator<ShopInfo>() {
////                    public int compare(ShopInfo arg0, ShopInfo arg1) {
////                        return arg0.getAreaLong().compareTo(arg1.getAreaLong());//倒叙排列
////                    }
////                });
//
//
//                //默认按照距离排序
//                Collections.sort(list, new Comparator<ShopInfo>() {
//                    public int compare(ShopInfo arg0, ShopInfo arg1) {
//                        return arg0.getDistinct().compareTo(arg1.getDistinct());//倒叙排列
//                    }
//                });
//            }
//        } else {
//            list = ShopMemory.getInstance().list(typeId, city, county, region, content, false);//该城市店铺列表
//        }
//
//        if (!ValidateUtil.isAbsList(list)) {
//            return AjaxResult.successResult(0, null);
//        }
//
//        if (ValidateUtil.isNotAbsInteger(page) || page < 1) {
//            page = 1;
//        }
//        if (ValidateUtil.isNotAbsInteger(size) || size < 1) {
//            size = 10;
//        }
//
//        //把推荐的店铺放在上面
//        List<ShopInfo> reList = new ArrayList<>();
//        if (ValidateUtil.isAbsList(list)) {
//            for (int i = 0; i < list.size(); i++) {
//                if (null == list.get(i)) {
//                    continue;
//                }
//                if (0 == 1 - list.get(i).getIsRecommend()) {
//                    reList.add(list.get(i));
//                }
//            }
//            for (int i = 0; i < list.size(); i++) {
//                if (null == list.get(i)) {
//                    continue;
//                }
//                if (0 == list.get(i).getIsRecommend()) {
//                    reList.add(list.get(i));
//                }
//            }
//        }
//
//
//        JYPageUtils.PageList pageList = JYPageUtils.getList(reList, page, size);
//        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
//            List<ShopInfoAndGameVO> voList = new ArrayList<ShopInfoAndGameVO>();
//            for (int i = 0; i < pageList.list.size(); i++) {
//                if (null == pageList.list.get(i)) {
//                    continue;
//                }
////                ShopInfoVO shopInfoVO = new ShopInfoVO();
////                try {
////                    ObjectUtils.copyPropertiesExclude(pageList.list.get(i), shopInfoVO, null);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                    continue;
////                }
////                if (null == shopInfoVO) {
////                    continue;
////                }
//
//
//                ShopInfoAndGameVO shopInfoVO = getShop(null, (ShopInfo) pageList.list.get(i), true);
//                if (null == shopInfoVO) {
//                    continue;
//                }
//
//                List<RegionInfoVO> relationList = Shop.getRegionListOfShop(shopInfoVO.getId());
//                if (ValidateUtil.isAbsList(relationList)) {
//                    shopInfoVO.setRegions(relationList);
//                }
//                voList.add(shopInfoVO);
//            }
//
//            if (ValidateUtil.isAbsList(voList)) {
//                return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
//            }
//        }

        return AjaxResult.successResult(0, 0, null);
    }


    // 团购商家获取商家类型 首页推荐商家分类
    @RequestMapping(method = RequestMethod.POST, value = "/group/shop/withGame/list")
    @ResponseBody
    public String group_list_with_game(String token, String content,
                                       String sysAppKey,
                                       Integer typeId,
                                       String city,
                                       Double lng, Double lat,
                                       Long agentId,
                                       Integer orderType, //排序方式
                                       String filterType,
                                       Integer needGoodsCount, // 店铺需要返回商品列表
                                       Integer isRecommend,// 是否获取推荐店铺
                                       Integer isPreference,// 是否获取推荐店铺
                                       Integer page, Integer size) {

        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请先选择城市");
        }
        FilterConditionUtils filterConditionUtils = FilterConditionUtils.getInstance();
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            filterConditionUtils.setCheckCloudSquareShop(true);
        }
        filterConditionUtils.setSysAppKey(sysAppKey);
        Integer needGoods = 0;
        if (needGoodsCount != null && needGoodsCount > 0) {
            needGoods = 1;
        }
        boolean isR = false;
        boolean checkR = false;
        if (null != isRecommend) {
            checkR = true;
            if (0 == 1 - isRecommend) {
                isR = true;
            }
        }
        JYPageUtils.PageList pageList = ShopListMan.getGroupShopList(user,//获取不同类型的店铺 用户端  包含活动信息
                true,//checkTypeId
                typeId,//typeId
                city,//city
                agentId,
                lng, lat,
                content,//content
                checkR,//checkRecommend
                isR,//isRecommend
                (isPreference != null && isPreference == 1),
                (isPreference != null && isPreference == 1),
                orderType,
                filterType,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                filterConditionUtils,
                page, size);
        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.list, pageList.totalCount);
        }
        return AjaxResult.successResult(null, 0);
    }

    //获取不同类型的店铺 用户端  包含活动信息 也搜索了商品信息
    @RequestMapping(method = RequestMethod.POST, value = "/shop/withGame/list/v2")
    @ResponseBody
    public String list_with_(String token, String content,
                             Integer typeId,
                             String city,
                             Double lng, Double lat,
                             Integer searchType, String province, String county,
                             Long regionId,
                             Long agentId, //精确的商圈(等我5分钟在用)
                             Integer orderType,//排序方式
                             String filterType,
                             String sysAppKey,
                             Integer isGroupShop, // 是不是团购商家
                             Integer needGoods, // 店铺需要返回商品列表
                             Integer needGoodsCount, // 店铺需要返回商品列表
                             Integer page, Integer size) {

        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }

        if (null != SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG && 0 == 1 - SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG) {

        } else {
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("请先选择城市");
            }
        }
        FilterConditionUtils filterConditionUtils = FilterConditionUtils.getInstance();
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            filterConditionUtils.setCheckCloudSquareShop(true);
        }
        filterConditionUtils.setSysAppKey(sysAppKey);
        JYPageUtils.PageList pageList = ShopListMan.getShopListV2(user,//获取不同类型的店铺 用户端  包含活动信息
                true,//checkTypeId
                typeId,//typeId
                city,//city
                regionId,//regionId
                agentId,
                lng, lat,
                content,//content
                false,//checkRecommend
                null,//isRecommend
                false,//checkIsPreference
                null,//isPreference
                true,//hasGameInfo
                orderType,
                filterType,
                isGroupShop,
                needGoods, // 店铺需要返回商品列表
                needGoodsCount, // 店铺需要返回商品列表
                filterConditionUtils,
                page, size);
        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }
        return AjaxResult.successResult(0, 0, null);
    }


    //获取所有的店铺，不分页
    @RequestMapping("/admin/shop/list/all")
    @ResponseBody()
    public String list_all(String token, @RequestParam(defaultValue = "0") Long shopTypeId) {

        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
        }

        String agent = "";
        String agentP = "";
        if (user.getUserType() == UserType.ADMIN) {
            agent = " left join " + PojoTables.SHOP_AGENT_RELATION + " sar on sar.shopId=si.id and sar.delFlag=0 " +
                    " left join " + PojoTables.USER_AGENT_RELATION + " uar on uar.agentId=sar.agentId and uar.delFlag=0 ";
            agentP = " and uar.username='" + user.getUsername() + "' ";
        }

        String sql = "select DISTINCT si.* from " + PojoTables.ShopInfo + " si " +
                "left join " + PojoTables.ShopTypeRelation + " str on si.id=str.shopId " + agent +
                "where si.delFlag=0 and str.delFlag=0 " + agentP;

        String sureShopType = " and str.shopTypeId=" + shopTypeId;
        String unShopType = " and str.shopTypeId!=" + shopTypeId;
        List<ShopInfoVO> list = null;
        List<ShopInfoVO> list2 = null;
        try {
            list = (List<ShopInfoVO>) UserDaoSql.getInstance().list(ShopInfoVO.class, sql + sureShopType);
            list2 = (List<ShopInfoVO>) UserDaoSql.getInstance().list(ShopInfoVO.class, sql + unShopType);
        } catch (SQLException e) {
            return AjaxResult.errorResult(e.getMessage());
        }
        if (ValidateUtil.isAbsList(list)) {
            list = list.stream().map(l -> {
                l.setIsShopType(true);
                return l;
            }).collect(Collectors.toList());
            if (ValidateUtil.isAbsList(list2)) {
                list.addAll(list2);
            }
            list = list.stream().map(l -> {
                List<ShopTypeInfoVO> typeInfoVOList = new ArrayList<ShopTypeInfoVO>();
                List<Integer> typeList = ShopTypeRelationMemory.getInstance().shopTypeList(l.getId());
                for (int j = 0; j < typeList.size(); j++) {
                    if (null == typeList.get(j)) {
                        continue;
                    }

                }
                l.setShopType(typeInfoVOList);
                if (ValidateUtil.isNotNull(l.getImageUrl()) && ValidateUtil.isNotNetUrl(l.getImageUrl())) {
                    String thumb = ImageService.getThumbnailImgUrl(l.getImageUrl(), l.getImgUpVer(), l.getThumbnailState());
                    l.setImageThumbnailUrl(thumb);
//                    l.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + l.getImageUrl());
                    l.setImageUrl(ImageService.getImgUrl(l.getImgUpVer()) + l.getImageUrl());
                }
                return l;
            }).collect(Collectors.toList());
        }
        return AjaxResult.successResult(list);
    }

    @RequestMapping("/admin/shop/type/modify")
    @ResponseBody
    public String addShop_type(String token, Integer shopTypeId, Long shopId, Integer status) {

        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
        }
        if (null == shopTypeId) {
            return AjaxResult.errorResult("未选择行业");
        }
        if (null == shopId) {
            return AjaxResult.errorResult("未选择店铺");
        }
        if (null == status) {
            return AjaxResult.errorResult("未选择选中状态");
        }
        String sql = "select * from shop_type_relation where delFlag=0 and shopId=" + shopId + " and shopTypeId=" + shopTypeId;

        List<HashMap<String, Object>> list = null;
        try {
            list = UserDaoSql.getInstance().queryBySql(sql);
        } catch (SQLException e) {
            return AjaxResult.errorResult(e.getMessage());
        }
        if (status == 0 && ValidateUtil.isAbsList(list)) {
            String sqlUp = "update shop_type_relation set delFlag=1 where delFlag=0 and shopId=" + shopId + " and shopTypeId=" + shopTypeId;
            try {
                UserDaoSql.getInstance().executeBySql(sqlUp);
            } catch (Exception e) {
                return AjaxResult.errorResult(e.getMessage());
            }
        }
        if (status == 1 && list.size() == 0) {
            ShopTypeRelation relation = new ShopTypeRelation();
            relation.setCreateTime(new Date().getTime());
            relation.setShopId(shopId);
            relation.setShopTypeId(shopTypeId);
            relation.setDelFlag(0);
            relation.setCreateUser(user.getUsername());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ShopTypeRelation, relation);
            } catch (Exception e) {
                return AjaxResult.errorResult(e.getMessage());
            }
        }
        ShopTypeRelationMemory.getInstance().modifyByShopId(shopId);
        return AjaxResult.successResult();
    }

    // 获取店铺的合计信息
    @RequestMapping("admin/shop/money/counts")
    @ResponseBody
    public String info(String token) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
        }
        String sql = "SELECT SUM(IFNULL(uwp.money,0)) counts FROM shop_info si " +
                "LEFT JOIN user_wallet uwp ON uwp.username=si.ownUsername AND uwp.delFlag=0 " +
                (user.getUserType() == UserType.ADMIN ? ("LEFT JOIN shop_agent_relation sar ON sar.shopId=si.id AND sar.delFlag=0 ") : "") +
                (user.getUserType() == UserType.ADMIN ? ("LEFT JOIN user_agent_relation uar ON uar.agentId=sar.agentId AND sar.delFlag=0 ") : "") +
                "WHERE si.delFlag=0 " +
                (user.getUserType() == UserType.ADMIN ? (" and uar.username='" + user.getUsername()) + "'" : "");

        List<HashMap<String, Object>> list = null;
        try {
            list = UserDaoSql.getInstance().queryBySql(sql);
        } catch (Exception e) {
            return AjaxResult.errorResult(e.getMessage());
        }
        return AjaxResult.successResult(list);
    }

    //获取不同类型的店铺   管理后台
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/list")
    @ResponseBody
    public String list_admin(String token, String content,
                             Integer isRecommend,  // 是否获取推荐店铺
                             Integer typeId,
                             String city,
                             Double lng, Double lat,
                             String region,
                             Integer orderType, // 排序方式 1 编号升序 2 编号降序
                             Long regionId,
                             Integer getNextLevel,  // 是不是要获取他的下一级代理的
                             Integer shopTag,           // 商家标签
                             Long agentId, //精确的商圈(等我5分钟在用)
                             String searchType, String province, String county,
                             Integer shopRole,    // 店铺用途 1.正常店铺  2. 品牌内页
                             Long shopTipId,//店铺标签id
                             Integer isSeriesSale,//是否批发商
                             @RequestParam(defaultValue = "1") Integer shopCategory,// 商家类型
//                             Integer isGroupShop,//是否团购商家  SHOP_GROUP_TYPE// 0普通商家 1团购商家 2既是团购又是普通
                             Integer needExtra,// 是否需要额外信息
                             Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        Long totalCount = 0l;
        List<ShopInfo> reList = null;
        //业务员
        if (ValidateUtil.isNotNull(token) && null != user && 0 == UserType.BUSINESS_MAN - user.getUserType()) {
            //只获取自己所管辖的店铺
            StringBuffer sb = new StringBuffer();
            sb.append(" from ");
            sb.append(PojoTables.ShopInfo);
            sb.append(" where delFlag =0 and businessUsername = '").append(user.getUsername()).append("'");
            if (ValidateUtil.isNotNull(content)) {
                sb.append(" and (shopName like '%").append(content).append("%'");
                sb.append(" or ownName like '%").append(content).append("%'");
                sb.append(" or ownUsername like '%").append(content).append("%'");
                sb.append(" or telephone like '%").append(content).append("%')");
            }
            sb.append(" and (shopCategory&").append(shopCategory).append(") > 0 ");
            sb.append(" and (cloudShopType&").append(CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE).append(") <= 0 ");
            try {
                //数量
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());

                //数据
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select * ").append(sb.toString());
                sbSql.append("limit ").append((page - 1) * size).append(",").append(size);
                reList = (List<ShopInfo>) UserDaoSql.getInstance().list(ShopInfo.class, sbSql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }

        } else {
            List<ShopInfo> list = null;
            if (ValidateUtil.isNotNull(token) && null != user && 0 == UserType.AGENT_MANAGER - user.getUserType()) {
                // 区域管理
//                List<ShopInfo> list = null;
                if (agentId != null) {
                    // 查看代理
                    if (!CityAgentMemory.getInstance().cityAgentInAgentManger(user.getUsername(), agentId)) {
                        return AjaxResult.successResult(null, 0);
                    } else {
                        list = ShopMan.listOfAgentId(agentId, typeId, shopTipId, content, isSeriesSale, shopCategory);
                    }
                } else {
                    List<CityAgent> cityAgentList = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
                    if (cityAgentList == null || cityAgentList.isEmpty()) {
                        return AjaxResult.successResult(null, 0);
                    }
                    list = new ArrayList<>();
                    Set<Long> agentIdSet = cityAgentList.stream().map(b -> b.getId()).collect(Collectors.toSet());
                    for (Long tempAgentId : agentIdSet) {
                        List<ShopInfo> tempList = ShopMan.listOfAgentId(tempAgentId, typeId, shopTipId, content, isSeriesSale, shopCategory);
                        if (ValidateUtil.isAbsList(tempList)) {
                            list.addAll(tempList);
                        }
                    }
                }
            }  else {
//                List<ShopInfo> list = null;
                if (ValidateUtil.isID(agentId)) {
                    list = ShopMan.listOfAgentId(agentId, typeId, shopTipId, content, isSeriesSale, shopCategory);
                } else {
                    String cityStr = city;
                    String countyStr = county;
                    if (ValidateUtil.isLatLng(lat, lng)) { //有经纬度根据经纬度来
                        LocationBean locationBean = null;
                        //根据经纬度解析出当前城市
                        try {
                            locationBean = LocationUtils.getCityBean(lat, lng);
                        } catch (Exception e) {
                            locationBean = null;
                        }

                        if (null != locationBean && null != locationBean.getRegeocode() && null != locationBean.getRegeocode().getAddressComponent()) {
                            LocationBean.RegeocodeBean.AddressComponentBean addressComponentBean = locationBean.getRegeocode().getAddressComponent();
                            cityStr = addressComponentBean.getCity();//市
                            countyStr = addressComponentBean.getDistrict();//区县
                            if (ValidateUtil.isNotNull(cityStr) && "市".equalsIgnoreCase(cityStr.substring(cityStr.length() - 1, cityStr.length()))) {
                                cityStr = cityStr.substring(0, cityStr.length() - 1);
                            }
                        }
                    }
                    if (ValidateUtil.isID(regionId)) {
                        list = new ArrayList<ShopInfo>();
                        List<ShopRegionRelation> relationList = ShopRegionRelationMemory.getInstance().listOfRegionId(regionId);
                        if (ValidateUtil.isAbsList(relationList)) {
                            for (int i = 0; i < relationList.size(); i++) {
                                if (null == relationList.get(i)) {
                                    continue;
                                }
                                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(relationList.get(i).getShopId());
                                if (null == shopInfo) {
                                    continue;
                                }

                                //是否为批发商
                                if (null != shopInfo.getIsSeriesSale() && null != isSeriesSale && 0 != isSeriesSale - shopInfo.getIsSeriesSale()) {
                                    continue;
                                }
                                // 创业商圈
                                if (null != shopInfo.getCloudShopType() && (shopInfo.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE) > 0) {
                                    continue;
                                }
                                // 是不是指定商家的
                                if (shopInfo.getShopCategory() != null && !ShopCategoryMan.validShopType(shopCategory, shopInfo.getShopCategory())) {
                                    continue;
                                }
                                if (ValidateUtil.isID(shopTipId) && !ShopTipRelationMemory.getInstance().shopHasTipId(shopInfo.getId(), shopTipId)) {
                                    continue;
                                }
                                list.add(shopInfo);
                            }
                        }
                    } else {
                        list = new ArrayList<ShopInfo>();
                        Boolean checkRecommendBo = false;
                        Boolean isRecommendBo = false;
                        if (ValidateUtil.isAbsInteger(isRecommend)) {
                            checkRecommendBo = true;
                            isRecommendBo = true;
                        }
                        List<ShopInfo> tempList = ShopMemory.getInstance().list(true, typeId,
                                cityStr, countyStr, region,
                                content,
                                checkRecommendBo, isRecommendBo,
                                false,
                                false,
                                shopRole,
                                isSeriesSale,
                                shopCategory,
                                shopTipId, false, CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_ORDINARY);
                        if (ValidateUtil.isAbsList(tempList)) {
                            list.addAll(tempList);
                        }
                    }
                }
            }
            List<ShopInfo> shopInfoList = new ArrayList<>();
            if (ValidateUtil.isAbsList(list)) {
                // 删除商城的
                for (ShopInfo s : list) {
                    if (s.getCloudShopType() != null && (s.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE) > 0) {
                        continue;
                    }
                    // tag
                    if (shopTag != null) {
                        ShopInfoExtra extra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(s.getId());
                        if (null == extra) {
                            continue;
                        } else if (extra.getShopTag() == null || extra.getShopTag() - shopTag != 0) {
                            continue;
                        }
                    }
                    if (s.getIsIntegralShop() == null || s.getIsIntegralShop() == 0) {
                        shopInfoList.add(s);
                    } else {
                        // 积分商城
                        continue;
                    }
                }
                Collections.sort(shopInfoList, new Comparator<ShopInfo>() {
                    public int compare(ShopInfo arg0, ShopInfo arg1) {
                        return ValidateUtil.isAbsInteger(orderType) && 0 != 1 - orderType ? arg1.getOrderNo().compareTo(arg0.getOrderNo()) : arg0.getOrderNo().compareTo(arg1.getOrderNo());
                    }
                });
            }
            if (!ValidateUtil.isAbsList(shopInfoList)) {
                return AjaxResult.successResult(null, 0);
            }
            JYPageUtils.PageList pageList = JYPageUtils.getList(shopInfoList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                reList = (List<ShopInfo>) pageList.list;
                totalCount = Long.parseLong(pageList.totalCount + "");
            }
        }
        if (ValidateUtil.isAbsList(reList)) {
            List<ShopInfoVO> voList = new ArrayList<ShopInfoVO>();
            String shopId = "";
            for (int i = 0; i < reList.size(); i++) {
                if (null == reList.get(i)) {
                    continue;
                }
                ShopInfoVO shopInfoVO = ShopService.getInstance().getShopInfoVoDetailOne(null, reList.get(i));
                if (null == shopInfoVO) {
                    continue;
                }
                List<ShopTypeInfoVO> typeInfoVOList = ShopMan.listShopTypeInfoVoByShopId(shopInfoVO.getId());
                shopInfoVO.setShopType(typeInfoVOList);
                List<RegionInfoVO> relationList = ShopMan.getRegionListOfShop(shopInfoVO.getId());
                if (ValidateUtil.isAbsList(relationList)) {
                    shopInfoVO.setRegions(relationList);
                }
                // 店铺额外信息
                if (null != needExtra && 0 == 1 - needExtra) {
                    ShopInfoExtra extra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopInfoVO.getId());
                    if (null != extra) {
                        // 店铺标签
                        shopInfoVO.setShopTag(extra.getShopTag());
                        ShopInfoExtraVO extraVO = new ShopInfoExtraVO();
                        try {
                            ObjectUtils.copyPropertiesExclude(extra, extraVO);
                        } catch (Exception e) {
                            e.printStackTrace();
                            extraVO = null;
                        }
                        if (null != extraVO) {
                            shopInfoVO.setExtraVO(extraVO);
                        }
                    }
                }
                // 是否全国店铺
                if (null != SYS_SETTINGS.SHOW_SPECIAL_SHOP && 0 == 1 - SYS_SETTINGS.SHOW_SPECIAL_SHOP) {
                    HashSet<SpecialShopListInfo> set = SpecialShopListMemory.getInstance().listOfShopId(shopInfoVO.getId());
                    if (null != set && set.size() > 0) {
                        shopInfoVO.setSpecialShopInfos(new ArrayList<>(set));
                    }
                }
                // 修改商家的 登录账号
                if (SYS_SETTINGS.LOGIN_TYPE_BY != null && SYS_SETTINGS.LOGIN_TYPE_BY == 1) {
                    UserInfo info = UserInfoMemory.getInstance().getUserInfo(shopInfoVO.getOwnUsername());
                    if (info != null) {
                        shopInfoVO.setOwnUsername(info.getUsername());
                    }
                }
                if (i == 0) {
                    shopId += shopInfoVO.getId();
                } else {
                    shopId += "," + shopInfoVO.getId();
                }

                voList.add(shopInfoVO);
            }
            ShopListMan.assignmentShopApplyVerifyTime(voList);
            Map<Long, ShopInfoExtra> map = getShowCounts(shopId);
            if (map != null && !map.isEmpty()) {
                for (ShopInfoVO vo : voList) {
                    ShopInfoExtra infoExtra = map.get(vo.getId());
                    if (infoExtra != null) {
                        vo.setShowOrderCounts(infoExtra.getShowOrderCounts());
                        if (SYS_SETTINGS.UPDATE_SHOP_GOODS_COUNT == 1) {
                            vo
                                    .setShoppingGoodsCounts(infoExtra.getShoppingGoodsCounts())
                                    .setRescueGoodCounts(infoExtra.getRescueGoodCounts())
                                    .setServiceGoodsCounts(infoExtra.getServiceGoodsCounts())
                                    .setLeaseGoodCounts(infoExtra.getLeaseGoodCounts());
                        }
                    }
                }
            }
            if (ValidateUtil.isAbsList(voList)) {
                voList = voList.stream().map(l -> {
                    try {
                        Double money = UserWalletMemory.getInstance().getWallet(l.getOwnUsername()).getMoney();
                        if (null != money) {
                            l.setMoney(money);
                        } else {
                            l.setMoney(0.00);
                        }
                    } catch (Exception e) {
                        l.setMoney(0.00);
                    }
                    return l;
                }).collect(Collectors.toList());
            }
            return AjaxResult.successResult(voList, totalCount);
        }
        return AjaxResult.successResult(null, 0);
    }


    //获取已删除的店铺   管理后台
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/del/list")
    @ResponseBody
    public String list_admin(String token,
                             Long agentId, //精确的商圈(等我5分钟在用)
                             String province, String county,
                             String city,
                             @RequestParam(defaultValue = "1") Integer shopCategory,// 商家类型
                             Integer page, Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        String sql = " FROM shop_info si" +
                " LEFT JOIN shop_agent_relation sar ON sar.shopId = si.id " +
                " LEFT JOIN user_agent_relation uar ON uar.agentId = sar.agentId and uar.delFlag=0 " +
                " LEFT JOIN city_agent ca ON ca.id = sar.agentId " +
                " WHERE si.delFlag = 1  " +
                " and  (si.cloudShopType & " + CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE + ") <=0 " +
                (StringUtils.isNotEmpty(province) ? (" AND si.province='" + province + "'") : "") +
                (StringUtils.isNotEmpty(city) ? (" AND si.city='" + city + "'") : "") +
                (StringUtils.isNotEmpty(county) ? (" AND si.county='" + county + "'") : "") +
                (null != agentId ? (" AND sar.agentId=" + agentId + "") : "") +
                (null != shopCategory ? (" AND si.shopCategory=" + shopCategory + "") : "") +
                (user.getUserType() == UserType.ADMIN ? (" AND uar.username='" + user.getUsername() + "'") : "") +
                " ORDER BY si.updateTime DESC";
        String sqlList = "SELECT si.*,ca.name agentName ";
        String sqlCount = "SELECT count(1) counts  ";
        String limit = " LIMIT " + ((page - 1) * size) + "," + size;

        List<HashMap<String, Object>> list = null;
        Long totalCount = 0l;
        try {
            String sqls = sqlList + sql + limit;
            list = UserDaoSql.getInstance().queryBySql(sqls);
            totalCount = UserDaoSql.getInstance().getCount(sqlCount + sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("评论获取失败，请稍后再试");
        }
        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(totalCount, list.size(), list);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    private Map getShowCounts(String shopId) {
        Map<Long, ShopInfoExtra> map = null;
        String sql = "select * from shop_info_extra where delFlag = 0 and shopId in (" + shopId + ")";
        List<ShopInfoExtra> list = new ArrayList<>();
        try {
            list = (List<ShopInfoExtra>) UserDaoSql.getInstance().list(ShopInfoExtra.class, sql.toString());
        } catch (Exception e) {
            e.getMessage();
        }
        if (list != null) {
            map = list.stream().collect(Collectors.toMap(ShopInfoExtra::getShopId, Function.identity(), (b1, b2) -> (b2)));
        }
        return map;
    }

    /**
     * 获取指定区域 指定类型  有或者没有指定基础商品的店铺列表 20190223
     *
     * @param token
     * @param content
     * @param city
     * @param county
     * @param shopRole
     * @param baseGoodsId
     * @param isHasGood
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/admin/goods/shop/list")
    @ResponseBody
    public String list_shop_by_goods(String token,
                                     String content,
                                     String city,
                                     String county,
                                     Integer shopRole,
                                     Long baseGoodsId,
                                     Integer isHasGood, // 0 没有该商品 1. 有该商品
                                     Integer isSelling, // 是否在售
                                     Integer page,
                                     Integer size) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
        }
        // 权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限操作");
        }
        // 操作类型
        if (null == isHasGood) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        // 商品
        if (ValidateUtil.isNotID(baseGoodsId)) {
            return AjaxResult.errorResult("基础商品id不能为空");
        }

        // 城市处理
        if (ValidateUtil.isNotNull(city) && "市".equalsIgnoreCase(city.substring(city.length() - 1, city.length()))) {
            city = city.substring(0, city.length() - 1);
        }
        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }
        Long totalCount = 0L;
        List<ShopInfo> reList = null;
        List<ShopInfo> shopInfos = ShopMemory.getInstance().getCityShopList(city, county, content, shopRole);
        List<ShopInfo> shopInfoList = null;

        if (ValidateUtil.isAbsList(shopInfoList)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(shopInfoList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                reList = (List<ShopInfo>) pageList.list;
                totalCount = Long.parseLong(pageList.totalCount + "");
            }
        }
        if (ValidateUtil.isAbsList(reList)) {
            List<ShopInfoVO> voList = new ArrayList<ShopInfoVO>();
            for (int i = 0; i < reList.size(); i++) {
                if (null == reList.get(i)) {
                    continue;
                }
                ShopInfoVO shopInfoVO = ShopService.getInstance().getShopInfoVoDetailOne(null, reList.get(i));
                if (null == shopInfoVO) {
                    continue;
                }
                voList.add(shopInfoVO);
            }
            return AjaxResult.successResult(totalCount, voList.size(), voList);
        }
        return AjaxResult.successResult(0, 0, null);
    }


    // 获取店铺下拉框
    @RequestMapping(method = RequestMethod.POST, value = "admin/shop/select")
    @ResponseBody
    public String user_agent_select(String token, String username,
                                    @RequestParam(defaultValue = "1") Integer shopCategory, String city, String county, Integer isCityAgent //是否按代理获取 0否 1是
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        // todo 城市代理按自己商圈获取店铺(搜点)
        ArrayList<ShopInfo> voList = new ArrayList<>();
        List<ShopInfo> tempList = null;
        if (user.getUserType() == UserType.AGENT_MANAGER) {
            // 区域主管
            AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
            if (info == null) {
                return AjaxResult.successResult(0, null);
            }
            List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
            if (!ValidateUtil.isAbsList(cityAgents)) {
                return AjaxResult.successResult(0, null);
            }
            Set<Long> agentIdSet = cityAgents.stream().map(b -> b.getId()).collect(Collectors.toSet());
            List<Long> shopIdList = new ArrayList<>();
            for (Long agentId : agentIdSet) {
                List<Long> temp = ShopAgentRelationMemory.getInstance().listOfAgentId(agentId);
                if (ValidateUtil.isAbsList(temp)) {
                    shopIdList.addAll(temp);
                }
            }
            Set<Long> shopIdSet = new HashSet<>();
            shopIdSet = shopIdList.stream().collect(Collectors.toSet());
            tempList = new ArrayList<>();
            for (Long shopId : shopIdSet) {
                ShopInfo shop = ShopMemory.getInstance().getShopById(shopId);
                if (shop == null) {
                    continue;
                }
                if ((shopCategory & shop.getShopCategory()) <= 0) {
                    continue;
                }
                if (ValidateUtil.isNotNull(city) && !city.equals(shop.getCity())) {
                    continue;
                }
                if (ValidateUtil.isNotNull(county) && !county.equals(shop.getCounty())) {
                    continue;
                }
                tempList.add(shop);
            }
        } else if (null != isCityAgent && isCityAgent - 1 == 0) {
            //  tempList = ShopMemory.getInstance().list(false, null, city, null, null, null, false, false, SHOP_ROLE.NORMAL, isCityAgent, user.getUsername());
            // 根据代理账号获取店铺Id
            String sysCityAdminUsername = user.getUsername();
            if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(sysCityAdminUsername)) {
                sysCityAdminUsername = SysCityCompanyMan.getSysCompanyOwnUsername(sysCityAdminUsername);
            }

//            List<Long> shopIdList = getShopIdList(user.getUsername());
            List<Long> shopIdList = getShopIdList(sysCityAdminUsername);
            // List<ShopInfo> tempv2List = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, false, false, SHOP_ROLE.NORMAL, null, shopCategory, null, true);
            List<ShopInfo> tempv2List = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, false, false, SHOP_ROLE.NORMAL, null, shopCategory, null, true, CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_ORDINARY);
            if (ValidateUtil.isAbsList(tempv2List)) {
                tempList = new ArrayList<>();
                // 判断该店铺是否在该代理下
                for (int i = 0; i < tempv2List.size(); i++) {
                    if (null == tempv2List.get(i)) {
                        continue;
                    }
                    Long shopIdArr = tempv2List.get(i).getId();
                    if (ValidateUtil.isAbsList(shopIdList)) {
                        for (int j = 0; j < shopIdList.size(); j++) {
                            if (null == shopIdList.get(j)) {
                                continue;
                            }
                            if (shopIdArr - shopIdList.get(j) == 0) {
                                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopIdList.get(j));
                                if (null == shopInfo) {
                                    continue;
                                }
                                tempList.add(shopInfo);
                            }
                        }
                    }
                }
            }
        } else {
            // todo 管理后台按城市区域获取店铺
            // tempList = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, false, false, SHOP_ROLE.NORMAL, null, shopCategory, null, true);
            tempList = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, false, false, SHOP_ROLE.NORMAL, null, shopCategory, null, true, CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_ORDINARY);
//            tempList = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, SHOP_ROLE.NORMAL);
        }
        if (ValidateUtil.isAbsList(tempList)) {
//            tempList = tempList.stream().filter(bean -> isGroupShop == bean.getIsGroupShop()).collect(Collectors.toList());
            voList.addAll(tempList);
        }
        List<Object> re = null;
        if (ValidateUtil.isAbsList(voList)) {
            re = new ArrayList<>();
            for (int i = 0; i < voList.size(); i++) {
                Map<String, Object> data = new HashMap<>();
                data.put("shopId", voList.get(i).getId());
                data.put("shopUsername", voList.get(i).getOwnUsername());
                data.put("shopName", voList.get(i).getShopName());
                re.add(data);
            }
            if (ValidateUtil.isAbsList(re)) {
                return AjaxResult.successResult(re.size(), re);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    // 代理获取店铺下拉框
    @RequestMapping(method = RequestMethod.POST, value = "admin/shop/select/V2")
    @ResponseBody
    public String user_agent_select(String token, String city, String county, @RequestParam(defaultValue = "1") Integer shopCategory) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        List<ShopInfo> tempList = null;
        if (user.getUserType() == UserType.SUPER_ADMIN || user.getUserType() == UserType.SUPER_COMPANY) {
            // tempList = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, false, false, SHOP_ROLE.NORMAL, null, shopCategory, null, true);
            tempList = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, false, false, SHOP_ROLE.NORMAL, null, shopCategory, null, true, CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_ORDINARY);
//            tempList = ShopMemory.getInstance().list(false, null, city, county, null, null, false, false, SHOP_ROLE.NORMAL);
        } else {
            tempList = new ArrayList<>();
            // 代理
            String sysCityAdminUsername = user.getUsername();
            if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(sysCityAdminUsername)) {
                sysCityAdminUsername = SysCityCompanyMan.getSysCompanyOwnUsername(sysCityAdminUsername);
            }
            List<Long> shopIdList = getShopIdList(sysCityAdminUsername);
            Set<Long> shopIdSet = null;
            if (shopIdList == null || shopIdList.isEmpty()) {
                return AjaxResult.successResult(0, null);
            } else {
                shopIdSet = shopIdList.stream().collect(Collectors.toSet());
            }
            for (Long shopId : shopIdSet) {
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
                if (vaildCheckShopInfo(shopInfo, sysCityAdminUsername)) {
                    tempList.add(shopInfo);
                }
            }
        }
        if (ValidateUtil.isAbsList(tempList)) {
            List<Object> re = new ArrayList<>();
            for (int i = 0; i < tempList.size(); i++) {
                Map<String, Object> data = new HashMap<>();
                data.put("shopId", tempList.get(i).getId());
                data.put("shopUsername", tempList.get(i).getOwnUsername());
                data.put("shopName", tempList.get(i).getShopName());
                re.add(data);
            }
            if (ValidateUtil.isAbsList(re)) {
                return AjaxResult.successResult(re.size(), re);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    private static boolean vaildCheckShopInfo(ShopInfo shopInfo, String username) {
        if (shopInfo != null) {
            if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
                if ((StringUtils.isEmpty(shopInfo.getCityAdmin())) || (StringUtils.isNotEmpty(username) && (username.equals(shopInfo.getCityAdmin())))) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }
        return false;
    }
    //--------------------------------------------------------------------------------------------------------------------------
//    //获取店铺列表
//    private JYPageUtils.PageList getShopList2(UserInfo user,//用来判断是否收藏过
//                                              boolean checkTypeId,//检测不同类型店铺
//                                              Integcer typeId,//不同类型店铺（检测店铺类型时，此参数才有效）
//                                              String city,
//                                              Long regionId,
//                                              Long agentId,//精确商圈代理Id
//                                              Double lng, Double lat,
//                                              String ontent,//检索内容
//                                              Boolean checkRecommend,//是否检测是否推荐
//                                              Boolean isRecommend,//是否推荐（只有检测推荐时，此参数才有效）
//                                              boolean hasGameInfo,//是否包含活动信息
//                                              Integer orderType,//排序方式
//                                              Integer page, Integer size) {
//        List<ShopInfo> list = null;
//        if (ValidateUtil.isID(agentId)) {
//            list = ShopMan.listOfAgentId(agentId, content);
//        } else {
//            if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)) {
//                //精确商圈方式
//                if (null != SYS_SETTINGS.SHOP_MANAGE_TYPE && 0 == SHOP_MANAGE_TYPE_FREE_OR_AGENT.AGENT - SYS_SETTINGS.SHOP_MANAGE_TYPE) {
//                    //如果传入了经纬度  根据用户的经纬度 查看距离最近的商圈的数据
//                    CityAgentVO cityAgentVO = CityAgentMan.getCityAgent(city, lat, lng);
//                    if (null == cityAgentVO) {
//                        return null;
//                    }
//                    List<Long> shopIds = ShopAgentRelationMemory.getInstance().listOfAgentId(cityAgentVO.getId());
//                    if (ValidateUtil.isAbsList(shopIds)) {
//                        list = new ArrayList<>();
//                        for (int i = 0; i < shopIds.size(); i++) {
//                            if (null == shopIds.get(i)) {
//                                continue;
//                            }
//
//                            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopIds.get(i));
////                        if (null == shopInfo) {
////                            continue;
////                        }
////                        if (ValidateUtil.isNotAbsDouble(lat) || ValidateUtil.isNotAbsDouble(lng)) {
////                            continue;
////                        }
////
////                        //是否推荐
////                        if (checkRecommend && 0 != 1 - shopInfo.getIsRecommend()) {
////                            continue;
////                        }
////
////                        //是否所属类型
////                        if (checkTypeId && ShopTypeRelationMemory.getInstance().shopInType(shopInfo.getId(), typeId)) {
////                            continue;
////                        }
////
////                        //判断检索
////                        if (ValidateUtil.isNotNull(content) &&
////                                !(hasKeyword(shopInfo.getShopName(), content)
////                                        || hasKeyword(shopInfo.getAffiche(), content)
////                                        || hasKeyword(shopInfo.getRegion(), content)
////                                        || hasKeyword(shopInfo.getDescs(), content))) {//如果需要判断搜索，搜索内容不包含
////                            continue;
////                        }
//
//                            if (!isUsefulShop(shopInfo, lat, lng, checkRecommend, checkTypeId, typeId, content)) {
//                                continue;
//                            }
//
//                            shopInfo.setDistinct(Geohash.distance(lat, lng, shopInfo.getLat(), shopInfo.getLng()));
//                            list.add(shopInfo);
//                        }
//                    }
//
//                } else {
//                    Long areaPoint = Geohash.getArea(lat, lng);
//                    int range = 15;//大概是10公里
//                    if (ValidateUtil.isAbsInteger(SYS_SETTINGS.SHOP_RANGE)) {
//                        range = SYS_SETTINGS.SHOP_RANGE;
//                    }
//                    Set<Long> areaPoints = Geohash.getAroundArea(areaPoint, range);
//
//
//                    if (ValidateUtil.isID(regionId)) {
//                        List<ShopRegionRelation> relationList = ShopRegionRelationMemory.getInstance().listOfRegionId(regionId);
//                        if (ValidateUtil.isAbsList(relationList)) {
//                            for (int i = 0; i < relationList.size(); i++) {
//                                if (null == relationList.get(i)) {
//                                    continue;
//                                }
//                                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(relationList.get(i).getShopId());
//                                if (!isUsefulShop(shopInfo, lat, lng, checkRecommend, checkTypeId, typeId, content)) {
//                                    continue;
//                                }
//
//                                if (!areaPoints.contains(shopInfo.getAreaPoint())) {
//                                    continue;
//                                }
//
//                                shopInfo.setDistinct(Geohash.distance(lat, lng, shopInfo.getLat(), shopInfo.getLng()));
//                                list.add(shopInfo);
//                            }
//                        }
//                    } else {
//                        List<ShopInfo> tmp = ShopMemory.getInstance().list(checkTypeId, typeId,
//                                city, "", "",
//                                content,
//                                checkRecommend, isRecommend);//该城市店铺列表
//                        if (ValidateUtil.isAbsList(tmp)) {
//                            list = new ArrayList<>();
//                            for (int i = 0; i < tmp.size(); i++) {
//                                if (null == tmp.get(i)) {
//                                    continue;
//                                }
//                                if (ValidateUtil.isNotAbsDouble(lat) || ValidateUtil.isNotAbsDouble(lng)) {
//                                    continue;
//                                }
//                                if (ValidateUtil.isNotAbsLong(tmp.get(i).getAreaPoint())) {
//                                    continue;
//                                }
//                                if (!areaPoints.contains(tmp.get(i).getAreaPoint())) {
//                                    continue;
//                                }
//
//                                tmp.get(i).setDistinct(Geohash.distance(lat, lng, tmp.get(i).getLat(), tmp.get(i).getLng()));
//                                list.add(tmp.get(i));
//                            }
//                        }
//                    }
//
//                }
//
//                if (ValidateUtil.isAbsList(list)) {
//                    //modify by liumingyao 2017-11-29
////                Collections.sort(list, new Comparator<ShopInfo>() {
////                    public int compare(ShopInfo arg0, ShopInfo arg1) {
////                        return arg0.getDistinct().compareTo(arg1.getDistinct());//按距离排序
////                    }
////                });
//                    //modify by zhuwx 2017-12-04
////                Collections.sort(list, new Comparator<ShopInfo>() {
////                    // 1  先按序号升序，序号相同 则距离升序
////                    public int compare(ShopInfo arg0, ShopInfo arg1) {
////                        if (arg0.getOrderNo().compareTo(arg1.getOrderNo()) == 0) {
////                            return arg0.getDistinct().compareTo(arg1.getDistinct()) > 0 ? 1 : -1;
////                        } else {
////                            return (int) (arg0.getOrderNo() - arg1.getOrderNo());
////                        }
////                    }
////                });
//
//
//                    if (ValidateUtil.isNotAbsInteger(orderType)) {
//                        orderType = SHOP_LIST_ORDER_TYPE.AGGREGATE;
//                    }
//                    if (null != orderType) {
//                        switch (orderType) {
//                            case SHOP_LIST_ORDER_TYPE.AGGREGATE: {//综合排序
//                                Collections.sort(list, new Comparator<ShopInfo>() {
//                                    // 1  先按序号升序，序号相同 则距离升序
//                                    public int compare(ShopInfo arg0, ShopInfo arg1) {
//                                        if (arg0.getOrderNo().compareTo(arg1.getOrderNo()) == 0) {
//                                            return arg0.getDistinct().compareTo(arg1.getDistinct()) > 0 ? 1 : -1;
//                                        } else {
//                                            return (int) (arg0.getOrderNo() - arg1.getOrderNo());
//                                        }
//                                    }
//                                });
//                            }
//                            break;
//                            case SHOP_LIST_ORDER_TYPE.DISTANCE: {//距离排序
//                                Collections.sort(list, new Comparator<ShopInfo>() {
//                                    public int compare(ShopInfo arg0, ShopInfo arg1) {
//                                        return arg0.getDistinct().compareTo(arg1.getDistinct());//按距离排序
//                                    }
//                                });
//                            }
//                            break;
//                        }
//                    }
////                Collections.sort(list, new Comparator<ShopInfo>() {
////                    public int compare(ShopInfo arg0, ShopInfo arg1) {
////                        return arg0.getOrderNo().compareTo(arg1.getOrderNo());// 按 orderNo序号 升序
////                    }
////                });
//
//                } else {
//                    return null;
//                }
//            } else {
//                list = ShopMemory.getInstance().list(checkTypeId, typeId,
//                        city, "", "",
//                        content,
//                        checkRecommend, isRecommend);//该城市店铺列表  管理后台可能用到
//            }
//        }
//
//
//        if (!ValidateUtil.isAbsList(list)) {
//            return null;
//        }
//
//        //把推荐的店铺放在上面
//        List<ShopInfo> reList = new ArrayList<>();
//        if (!checkRecommend) {//检测了推荐 只有推荐了
//            if (ValidateUtil.isAbsList(list)) {
//                //把推荐的店铺放在上面
//                for (int i = 0; i < list.size(); i++) {
//                    if (null == list.get(i)) {
//                        continue;
//                    }
//                    if (0 == 1 - list.get(i).getIsRecommend()) {
//                        reList.add(list.get(i));
//                    }
//                }
//                //其他
//                for (int i = 0; i < list.size(); i++) {
//                    if (null == list.get(i)) {
//                        continue;
//                    }
//                    if (0 == list.get(i).getIsRecommend()) {
//                        reList.add(list.get(i));
//                    }
//                }
//            }
//        } else {
//            reList.addAll(list);
//        }
//
//        if (null == page || page < 1) {
//            page = 1;
//        }
//        if (null == size || size < 1) {
//            size = 10;
//        }
//
//        if (1 == page && reList.size() < size) {//不许要分页
//            List<ShopInfoAndGameVO> voList = new ArrayList<>();
//            for (int i = 0; i < reList.size(); i++) {
//                if (null == reList.get(i)) {
//                    continue;
//                }
//                ShopInfoAndGameVO shopInfoVO = getShop(user, reList.get(i), hasGameInfo);
//
//                if (null == shopInfoVO) {
//                    continue;
//                }
//                voList.add(shopInfoVO);
//            }
//
//            if (ValidateUtil.isAbsList(voList)) {
//                return new JYPageUtils.PageList(reList.size(), voList.size(), voList);
//            }
//        } else {
//            JYPageUtils.PageList pageList = JYPageUtils.getList(reList, page, size);
//            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
//                List<ShopInfoAndGameVO> voList = new ArrayList<>();
//                for (int i = 0; i < pageList.list.size(); i++) {
//                    if (null == pageList.list.get(i)) {
//                        continue;
//                    }
//                    ShopInfoAndGameVO shopInfoVO = getShop(user, (ShopInfo) pageList.list.get(i), hasGameInfo);
//
//                    if (null == shopInfoVO) {
//                        continue;
//                    }
//                    voList.add(shopInfoVO);
//                }
//
//                if (ValidateUtil.isAbsList(voList)) {
//                    return new JYPageUtils.PageList(reList.size(), voList.size(), voList);
//                }
//            }
//        }
//        return null;
//    }

    //    //获取店铺的简单信息
//    private ShopInfoAndGameVO getShop(UserInfo user, ShopInfo info, boolean hasGameInfo) {
//        ShopInfoAndGameVO shopInfoVO = new ShopInfoAndGameVO();
//        try {
//            ObjectUtils.copyPropertiesExclude(info, shopInfoVO, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        if (null == shopInfoVO) {
//            return null;
//        }
//        //登录用户判断是否收藏过
//        if (user != null && ShopLikeMemory.getInstance().isLike(user.getUsername(), shopInfoVO.getId())) {//登录用户判断是否收藏
//            shopInfoVO.setIsLike(1);
//        }
//
//
//        //获取店铺评分、星级、销量
//        ShopInfoExtra extraInfo = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopInfoVO.getId());
//        if (null != extraInfo) {
//            shopInfoVO.setStar(extraInfo.getStar());
//            shopInfoVO.setScore(extraInfo.getScore());
//            shopInfoVO.setOrderCounts(extraInfo.getOrderCounts());
//            shopInfoVO.setMonthOrderCount(extraInfo.getMonthOrderCount());
//        }
//
//        if (hasGameInfo) {
//            //获取店铺活动信息
//            List<GameInfoAndRulesVO> gameList = Game.listOfShopId(info.getId());
//            shopInfoVO.setGameList(gameList);
//        }
//
//        return shopInfoVO;
//    }
//
//    //检测店铺
//    private boolean isUsefulShop(ShopInfo shopInfo, Double lat, Double lng, boolean checkRecommend, boolean checkTypeId, Integer typeId, String content) {
//        if (null == shopInfo) {
//            return false;
//        }
//        if (ValidateUtil.isNotAbsDouble(lat) || ValidateUtil.isNotAbsDouble(lng)) {
//            return false;
//        }
//
//        //是否推荐
//        if (checkRecommend && 0 != 1 - shopInfo.getIsRecommend()) {
//            return false;
//        }
//
//        //是否所属类型
//        if (checkTypeId && !ShopTypeRelationMemory.getInstance().shopInType(shopInfo.getId(), typeId)) {
//            return false;
//        }
//
//        //判断检索
//        if (ValidateUtil.isNotNull(content) &&
//                !(hasKeyword(shopInfo.getShopName(), content)
//                        || hasKeyword(shopInfo.getAffiche(), content)
//                        || hasKeyword(shopInfo.getRegion(), content)
//                        || hasKeyword(shopInfo.getDescs(), content))) {//如果需要判断搜索，搜索内容不包含
//            return false;
//        }
//        return true;
//    }
//
//    private boolean hasKeyword(String target, String keyword) {
//        if (ValidateUtil.isNotNull(target) && target.contains(keyword)) {
//            return true;
//        }
//
//        return false;
//    }

    // 获取申请云商家的店铺
    @RequestMapping("/admin/cloud/shop/apply/list")
    @ResponseBody
    public String cloudShopApplayList(String token, String city, String county, Long agentId, Integer shopCategory, String content, @RequestParam(defaultValue = "1") Integer cloudShopApplyState, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        List<ShopInfo> list = new ArrayList<>();
        if (user.getUserType() == UserType.SUPER_ADMIN || SysCityCompanyMan.isSuperAdminCompanyUser(user.getUsername())) {
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("城市不能为空");
            }
            if (ValidateUtil.isID(agentId)) {
                List<Long> shopIds = ShopAgentRelationMemory.getInstance().listOfAgentId(agentId);
                for (Long shopId : shopIds) {
                    ShopInfo shop = ShopMemory.getInstance().getShopById(shopId);
                    if (shop != null) {
                        list.add(shop);
                    }
                }
            } else {
                List<ShopInfo> cityShopList = null;
                if (ValidateUtil.isNotNull(city)) {
                    cityShopList = ShopMemory.getInstance().getCityShopList(city, county, content, null);
                    if (ValidateUtil.isAbsList(cityShopList)) {
                        list.addAll(cityShopList);
                    }
                } else {
                    cityShopList = ShopMemory.getInstance().list();
                    if (ValidateUtil.isAbsList(cityShopList)) {
                        if (ValidateUtil.isNotNull(content)) {
                            cityShopList = cityShopList.stream().filter(b -> b != null && b.getShopName() != null && b.getShopName().contains(content)).collect(Collectors.toList());
                        }
                        list.addAll(cityShopList);
                    }
                }
            }
        }   else {
            return AjaxResult.successResult(null, 0);
        }
        // 过滤
        //
        List<ShopInfo> dataList = new ArrayList<>();
        if (ValidateUtil.isAbsList(list)) {
            for (ShopInfo info : list) {
                if (info == null) {
                    continue;
                }
                if (ValidateUtil.isNotNull(content) && (info.getShopName() == null || !info.getShopName().contains(content))) {
                    continue;
                }
                // 指定商家类型的数据
                if (shopCategory != null && (info.getShopCategory() & shopCategory) <= 0) {
                    continue;
                }
                if (cloudShopApplyState == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_PASS) {
                    if ((info.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_PROVIDE) <= 0) {
                        continue;
                    }
                } else if (cloudShopApplyState == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_ING || cloudShopApplyState == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_NO_PASS) {
                    if ((info.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_PROVIDE) > 0) {
                        continue;
                    }
                    ShopInfoExtra infoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(info.getId());
                    if (infoExtra == null) {
                        continue;
                    }
                    if (infoExtra.getCloudShopApplyState() != cloudShopApplyState) {
                        continue;
                    }
                } else {
                    continue;
                }
                dataList.add(info);
            }
        }
        // 升序
        Collections.sort(dataList, Comparator.comparingLong(ShopInfo::getId));
        JYPageUtils.PageList pageList = JYPageUtils.getList(dataList, page, size);
        List<ShopInfoVO> reList = new ArrayList<>();
        List<ShopInfo> shopInfoList = pageList.list == null ? Collections.EMPTY_LIST : (List<ShopInfo>) pageList.list;
        for (ShopInfo info : shopInfoList) {
            ShopInfoVO vo = info.convert2VO();
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getOwnUsername());
            if (userInfo != null) {
                vo.setOwnName(userInfo.getName());
            }
            reList.add(vo);
        }
        return AjaxResult.successResult(reList, dataList.size());
    }

}
